﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml;
using PmfWeb.Core.Web;

namespace PmfWeb.Core.Utility
{
    ///<summary>
    /// Xml文件操作类
    ///</summary>
    public class XmlUtils
    {
        private XmlDocument _xml;

        ///<summary>
        /// 构造器
        ///</summary>
        public XmlUtils()
        {
        }

        ///<summary>
        ///</summary>
        ///<param name="fileName"></param>
        public XmlUtils(string fileName)
        {
            if (String.IsNullOrEmpty(fileName)) throw new Exception("文件路径错误");
            string cacheKey = Path.GetFileName(fileName);
            _xml = LoadXml(fileName, cacheKey);
        }

        ///<summary>
        ///</summary>
        ///<param name="xPath"></param>
        ///<returns></returns>
        public XmlNodeList GetNodeList(string xPath)
        {
            if(null == _xml) return null;
            return _xml.SelectNodes(xPath);
        }

        


        private XmlDocument LoadXml(string fileName, string cachekey)
        {
            if(String.IsNullOrEmpty(fileName)) return null;
            if (!File.Exists(fileName)) return null;

            XmlDocument doc;
            try
            {
                doc = GetCachedDocument(cachekey);
                if(null == doc)
                {
                    doc = new XmlDocument();
                    doc.Load(fileName);
                    DataCache.SetCache(cachekey, doc, fileName);
                    return doc;
                }
            }
            catch
            {
                doc = null;
            }
            return doc;
        }

        private XmlDocument GetCachedDocument(string key)
        {
            object obj = DataCache.GetCache(key);
            if(null == obj) return null;
            return (XmlDocument)obj;
        }

    }
}
